package cn.itcast.bassm.controller;

import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import cn.itcast.bassm.mapper.UserMapper;
import cn.itcast.bassm.pojo.Push;
import cn.itcast.bassm.pojo.Returnxx;
import cn.itcast.bassm.pojo.Unitdoor;
import cn.itcast.bassm.pojo.Uploadfile;
import cn.itcast.bassm.pojo.User;
import cn.itcast.bassm.pojo.UserInformation;
import cn.itcast.bassm.pojo.Userformation;
import cn.itcast.bassm.pojo.Visitors;
import cn.itcast.bassm.pojo.test1;
import cn.itcast.bassm.service.PushService;
import cn.itcast.bassm.service.UserService;
import cn.itcast.bassm.util.readTxT;

import com.alibaba.fastjson.JSONObject;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

@RequestMapping("/user")
@Controller
public class UserController {
	
	@Autowired
	private UserService userService;
	
	@Autowired
	private PushService pushService;
	
	@Autowired
	private  UserMapper userMapper;
	


	
	@RequestMapping(value="/{id}",method=RequestMethod.GET)
	public ResponseEntity<User> queryUserById(@PathVariable("id")int id){
		
		try {
			User user= userService.queryUserById(id);
			return ResponseEntity.ok(user); 
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null);	
	}

	
	/**
	 * 告警推送.
	 * @param Pushmessage
	 */
	@RequestMapping(value="/savemsg",method=RequestMethod.POST)
	public void savemsg(@RequestBody String Pushmessage){
		JSONObject jsonObject = JSONObject.parseObject(Pushmessage);
		String scenePath1 = jsonObject.getString("scenePath");
		String tt ="http://127.0.0.1:8080";
		String strimg=scenePath1.replaceAll(tt, "");
		String scenePath = "http://192.168.1.230:8080"+strimg;
		System.out.println(strimg);
		//long datelong = jsonObject.getLongValue("timestamp");
		pushService.savePush(scenePath);
	}
	
	/**
	 * 登陆
	 */
	@RequestMapping(value="/addlogin",method=RequestMethod.POST)
	@ResponseBody
	public Userformation addlogin(String username,String password){
		System.out.println("登录");
		Userformation userformation = new Userformation();
		userformation= userService.queryUserByPowrd(username, password);
		return userformation;
	}
	
	
	/**
	 * 人脸检测
	 */
	/*//addWhitePersion
	@RequestMapping(value="/addWhitePersion",method=RequestMethod.POST)
	@ResponseBody
	public String addWhitePersion(String filepath, String name, String phone,String detailed,String sex,String sfzid,int state){
		boolean msg=userService.addWhitePersion(filepath,name,phone,detailed,sex,sfzid,state);
		if(!msg){
			String usermsg="0";
			return usermsg;
		}else {
			String usermsg="1";
			return usermsg;
		}
	}*/
	/**
	 * 保存用户信息
	 */
	
	@RequestMapping(value="/UserInformation",method=RequestMethod.POST)
	@ResponseBody
	public String UserInformation(MultipartFile file, String name, String phone,String sfzid,String detailed,String sex){
		String phong=phone;
		int state=1;
		String msg = userService.addUserInformation(file, name, sex, phong,sfzid, detailed,state);
		return msg;
	}
	
	
	/**
	 * 用户信息列表展示
	 */
	@RequestMapping(value="/ListUserInformation",method=RequestMethod.GET)
	public String ListUserInformation(ModelMap map){	
		List<UserInformation> userinformation=pushService.finPushUser();
		map.addAttribute("userinformation",userinformation);
		return "showAll";
	}

	/**
	 * 选择图片人脸检测
	 */
	@RequestMapping(value="/UserInformationFist",method=RequestMethod.POST)
	@ResponseBody
	public String UserInformationFist(String filepath){;
	String msg=userService.addFacePathFist(filepath);
		return msg;
	}
	
	
	/**
	 * 彩之云授权人员列表
	 */
	@RequestMapping(value="/czyuser",method=RequestMethod.GET)
	public String czyuser( String pageNow, String Celladdress,Model model){
		String str=Celladdress;	 
		byte[] bytes;
		byte[] bytes2;
		try {
			bytes = str.getBytes("ISO-8859-1");
			String name=new String(bytes,"utf-8");
			this.userService.showProductsByPageczy(pageNow,name,model);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} 
		return "showAllczysq";
	}
	
	
	/**
	 * 允许加入白名单
	 * @throws Throwable 
	 */
	@RequestMapping(value="/addUserInformationFist",method=RequestMethod.POST)
	@ResponseBody
	public Returnxx addUserInformationFist(String id) throws Throwable{
		Returnxx rb = new Returnxx();
		
		    rb= userService.upuseronetwonuber(id);
		
		return rb;
	}
	
	/**
	 * 分页查询用户数据展示
	 */
	@RequestMapping(value="/showMyProduct",method=RequestMethod.GET)
	public String showMyProduct(String pageNow, Model model){	
		//this.userService.showProductsByPage(pageNow,model);
		return "showAll";
	}
	
	/**
	 * 禁止用户加入白名单
	 * @throws UnsupportedEncodingException 
	 */
	@RequestMapping(value="/DeleUserInformationFist",method=RequestMethod.GET)
	@ResponseBody
	public Returnxx DeleUserInformationFist(String id) throws UnsupportedEncodingException{
		Returnxx rb = new Returnxx();
		try {
		    int idone = Integer.parseInt(id);
		    rb= userService.deleonetwonuber(idone);
		} catch (NumberFormatException e) {
		    e.printStackTrace();
		}
		return rb;
	}
	
	
	/**
	 * 查询用户图片返回注册页面
	 */
	@RequestMapping(value="/showMyUserImg",method=RequestMethod.GET)
	public String showMyUserImg( Model model){	
		List<Push>push=pushService.showFinUserImg();
		model.addAttribute("push", push);
		return "add2";
	}
	
	/**
	 * 推送头像注册页面保存用户信息
	 */
	@RequestMapping(value="/UserImgFistToto",method=RequestMethod.POST)
	@ResponseBody
	public String UserImgFistTo(String urlimgfisto, String name, String phone,String sfzid,String detailed,String sex){
		String phong=phone;
		int state=1;
		String str =urlimgfisto;
		String txtPath ="/usr/local/tomcat/tomcat8/webapps/configSEX.txt";
		String TimeSex=readTxT.readTxtLine(txtPath, 2);
		String strimg=str.replaceAll(TimeSex, "");
		String msg = userService.addUserImgToFist(strimg, name, sex, phong, sfzid, detailed, state);
		return msg;
	}
	
	/**
	 * 用户信息列表删除
	 */
	@RequestMapping(value="/DeleUserImg",method=RequestMethod.POST)
	@ResponseBody
	public Returnxx DeleUserImg(String yid,String yaddress){
		Returnxx rb = new Returnxx();
		rb = userService.deleimg(yid,yaddress);
		return rb;
	}
	
	/**
	 * 选择图片检测人脸
	 */
	@RequestMapping(value="/UseImgUploadFin",method=RequestMethod.POST)
	@ResponseBody
	public String UserImgUpload(MultipartFile file){
		String msg =userService.UserimgUploadFin(file);
		return msg;
	}
	
	/**
	 * 展示页面超级管理员
	 */
	@RequestMapping(value="/visitorsuser1",method=RequestMethod.GET)
	public String visitorsuser1( Model model){
		return "NewFile";
	}
	
	/**
	 * 展示页面业主
	 */
	@RequestMapping(value="/visitorsuser2",method=RequestMethod.GET)
	public String visitorsuser2(String pageNow, String Celladdress,Model model){
		System.out.println("展示页面业主");
		String str=Celladdress;	 
		byte[] bytes;
		byte[] bytes2;
		try {
			bytes = str.getBytes("ISO-8859-1");
			String name=new String(bytes,"utf-8");
			this.userService.showProductsByPage(pageNow,name,model);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} 
		return "showAll";
	}
	
	/**
	 * 展示页面访客
	 */
	@RequestMapping(value="/visitorsuser3",method=RequestMethod.GET)
	public String visitorsuser3( Model model){
		return "NewFile3";
	}
	
	/**
	 * 根据用户名或者手机好进行查询
	 */
	@RequestMapping(value="/selectFinPhoneorUserName",method=RequestMethod.GET)
	public String selectFinPhoneorUserName(String phonename,String nameonefin,String yaddressall,String pageNow,Model model){
		System.out.println("根据用户名或者手机好进行查询");
		String str=nameonefin;
		String str2=yaddressall;
		byte[] bytes;
		byte[] bytes2;
		try {
			bytes = str.getBytes("ISO-8859-1");
			bytes2 = str2.getBytes("ISO-8859-1");
			String name=new String(bytes,"utf-8");
			String name2=new String(bytes2,"utf-8");
			String nameonefinname =name;
			String yaddressallall=name2;
			this.userService.selectFinPhoneorUserNamefin(phonename, nameonefinname,yaddressallall, pageNow, model);
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
		return "showAllfin";
		}
	
	/**
	 * 根据用户的id 小区地址 进行查询
	 */
	@RequestMapping(value="/selectFinPhoneorUserNameLou",method=RequestMethod.GET)
	public String selectFinPhoneorUserNameLou(String yid,String yaddress, Model model){	
		String str=yaddress;
		byte[] bytes;
		try {
			bytes = str.getBytes("ISO-8859-1");
			String name=new String(bytes,"utf-8");
			String yaddressallall=name;
		List<Uploadfile>products = new ArrayList<Uploadfile>();
		List<Unitdoor> unitdoor = new ArrayList<Unitdoor>();
		String number="all";
			products = userService.selectloufin(yid);
			unitdoor = userService.selectloufinuser(yaddressallall);
			model.addAttribute("products", products);  
			model.addAttribute("unitdoor", unitdoor);  
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return "oneShowAll";
	}
	
	/**
	 * 用户信息修改保存
	 * @throws UnsupportedEncodingException 
	 */
	@RequestMapping(value="/upUseroneFinset",method=RequestMethod.POST)
	@ResponseBody
	public Returnxx upUseroneFinset(String yid,String ydetailed,String yaddress,String yname,String cardnumber,String yidcar,String roomandnumber,String unitbuilding) throws UnsupportedEncodingException{
		Returnxx rb = new Returnxx();
		try {
		    int id = Integer.parseInt(yid);
		    
			rb=userService.UpselcetUserXxFin(id, ydetailed, yaddress,yname,cardnumber,yidcar,roomandnumber,unitbuilding);
			
		} catch (NumberFormatException e) {
		    e.printStackTrace();
		}
			
		return rb;	
	}
	
	/**
	 *卡号注册页面跳转
	 */
	@RequestMapping(value="/kanuberload",method=RequestMethod.GET)
	public String kanuberload( String yaddress,Model model){
		String str=yaddress;
		byte[] bytes;
		try {
			bytes = str.getBytes("ISO-8859-1");
			String address=new String(bytes,"utf-8");
			List<Unitdoor> unitdoor = new ArrayList<Unitdoor>();
			unitdoor = userService.selectloufinuser(address);
			model.addAttribute("address", address); 
			model.addAttribute("unitdoor", unitdoor);  
		}catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return "adduserxi";
	}
	
	/**
	 *管理员卡号注册页面跳转
	 */
	@RequestMapping(value="/adminkanuberload",method=RequestMethod.GET)
	public String adminkanuberload( String yaddress,Model model){
		String str=yaddress;
		byte[] bytes;
		try {
			bytes = str.getBytes("ISO-8859-1");
			String address=new String(bytes,"utf-8");			
			model.addAttribute("address", address); ;  
		}catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return "addadminka";
	}
	
	/**
	 *快速注册卡号重复
	 */
	@RequestMapping(value="/Fastregistrationcardnumberrepeating",method=RequestMethod.GET)
	public String Fastregistrationcardnumberrepeating( String pageNow,String yaddress,Model model){
			
		String str=yaddress;
		byte[] bytes;
		try {
			bytes = str.getBytes("ISO-8859-1");
			String address=new String(bytes,"utf-8");			
			this.userService.showFastregistrationcardnumberrepeating(pageNow,address,model);
		}catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return "khcfshowAll";
	}
	
	/**
	 * 卡号注册用户保存
	 */
	@RequestMapping(value="/addkahaouser",method=RequestMethod.POST)
	@ResponseBody
	public Returnxx addkahaouser(String yname,String ysex,String cardnumber,String yaddress,String ydetailed ){
		Returnxx rb  = new Returnxx();
		rb = userService.savekahaouser(yname, ysex, cardnumber, yaddress, ydetailed);	
		return  rb;
	}
	
	/**
	 * 管理员卡号注册用户保存
	 */
	@RequestMapping(value="/addkahaouserandadmin",method=RequestMethod.POST)
	@ResponseBody
	public Returnxx addkahaouserandadmin(String yname,String ysex,String cardnumber,String yaddress ){
		Returnxx rb  = new Returnxx();
		rb = userService.savekahaouserandadmin(yname, ysex, cardnumber, yaddress);	
		return  rb;
	}
	
	
	/**
	 * 删除用户(没有实际删除)
	 * @throws UnsupportedEncodingException 
	 */
	@RequestMapping(value="/deleteuserone",method=RequestMethod.POST)
	@ResponseBody
	public Returnxx deleteuserone(String yid,String yaddress ) throws UnsupportedEncodingException{
		Returnxx rb  = new Returnxx();
		String msg = null;
		/*String str=yaddress;
		byte[] bytes;
		bytes = str.getBytes("ISO-8859-1");
		String yaddress1=new String(bytes,"utf-8");*/
		Date data=new Date();
		SimpleDateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String updatetime = dateFormat.format(data);
        Date data2=new Date();
        SimpleDateFormat dateFormattwo=new SimpleDateFormat("yyyyMMdd");
        String idnumber = dateFormattwo.format(data2);
        Uploadfile upfile = userMapper.secletusergunone(yid);  
        String fast=upfile.getRegistrationandtype();
        String cardnumberandrepeat=upfile.getCardnumberandrepeat();
        String fastto="FastandRegistration";
        if(fast.equals(fastto)){//是快速注册类型
			String cardnumber = upfile.getCardnumber();
			String yaddressna = upfile.getYaddress();
			String binding="0";
			if(cardnumberandrepeat.equals("repeat")){//如果是快速注册，而且是重复的数据, 不对微信绑定表进行操作
				
			}else {
				userMapper.upandPublicandNumber(cardnumber,yaddressna,binding,yid);//更该用户在公众号中的 绑定的标识，删除之后让用户能再次绑定
			}
			
		}else {
			
			// 不是快速注册类型，不对微信绑定表做操作
			
		}
        try {
        	userMapper.deleteuserone(yid,updatetime);
        } catch (Exception e) {
        	e.printStackTrace();
        	msg="2";
        	rb.setMsg(msg);
        	rb.setDetailed(yaddress);
        	return rb;
        }
		
		msg="1";
		rb.setDetailed(yaddress);
		rb.setMsg(msg);
		return  rb;
	}
	
	/**
	 * 测试接口
	 */
	/**
	 * 卡号注册用户保存
	 */
	@RequestMapping(value="/Testfintwo",method=RequestMethod.POST, consumes = "application/json")
	@ResponseBody
	public String Testfintwo(@RequestBody String   json ){
		JsonParser parser = new JsonParser(); // 创建JSON解析器
         JsonObject object = (JsonObject) parser.parse(json); // 创建JsonObject对象
         String timesetend=object.get("starttime").getAsString();
         String dbid=object.get("dbid").getAsString();
         System.out.println(timesetend);
         System.out.println(dbid);
         String msg ="1";
		return msg;
	}
	
	
	/**
	 * 修改密码跳转页面
	 */
	@RequestMapping(value="/modifythepassword",method=RequestMethod.GET)
	public String modifythepassword( String yaddress,Model model){
		String str=yaddress;
		byte[] bytes;
		try {
			bytes = str.getBytes("ISO-8859-1");
			String address=new String(bytes,"utf-8");			
			model.addAttribute("address", address); ;  
		}catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return "xiugaimima";
	}
	
	/**
	 * 修改密码
	 */
	@RequestMapping(value="/modifythepasswordto",method=RequestMethod.POST)
	@ResponseBody
	public Returnxx modifythepasswordto(String yname,String ysex,String cardnumber,String yaddress ){
		String yuan=yname;//原密码
		String xin =cardnumber;//新密码
		String leixin = ysex;//修改类型
		Returnxx rb  = new Returnxx();
		rb = userService.modifythepasswordtolike(yuan,xin,leixin,yaddress);	
		return  rb;
	}
	
	
	
	/**
	 * 创建数据
	 */
	@RequestMapping(value="/chuangjian",method=RequestMethod.GET)
	@ResponseBody
	public String chuanjianshuju(){
		String yname1 ="testfiveq";
		String yfilename1 ="https://wwl.ycws.cc/image/upload/";
		String ysex="男";
		String yowner="其他";
		String yphone1="20170915";
		String yaddress="彩悦大厦";
		String ydetailed="10楼";

		String yindex="1";
		String ynumber="";
		String idnumber="20191010";
		
		for (int i = 1; i <17; i++) {
			Date data=new Date();
	        SimpleDateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	        String state = dateFormat.format(data);
	    	String createtime=state;
	    	String updatetime=state;
	    	String s=String.valueOf(i);
	    	String yname =yname1+s;
	    	String yphone=yphone1+s;
	    	String yfilename =yfilename1+"cydstests"+s+".jpg";
	    	String examine="1";
	    	userMapper.savetestoneuser(yfilename, yname, ysex, yowner, yphone, yaddress, ydetailed, createtime, updatetime, yindex, ynumber, idnumber,examine);

		}
		String msg="1";
		return msg;
	}
	
	
	/**
	 * @throws Throwable 
	 * 
	 */
	@RequestMapping(value="/chaxunshuju",method=RequestMethod.GET)
	@ResponseBody
	public String chaxunshuju() throws Throwable{
		List<Uploadfile> u = userMapper.chaxunuser();
		List<Visitors> v = userMapper.chaxunvisitors();
		for(int i =0;i<u.size();i++){
			Uploadfile uu = u.get(i);
			/*String urlString=uu.getYfilename();
			String facepath = pushService.saveJPG(urlString);*/
			String urlString=uu.getYfilename();
			String facepath =urlString;
			String name = uu.getYname();
			String phone = String.valueOf(uu.getYid());
			String sex = uu.getYsex();
			boolean msg =userService.addWhitePersion(facepath, name, phone, sex);
			if(msg){
				System.out.println("成导入"+phone);
			}else{
				System.out.println("导入失败"+phone);
			}
			
			
		}
		for(int j =0;j<v.size();j++){
			Visitors vv = v.get(j);
			/*String urlString =vv.getYimageurl();
			String facepath = pushService.saveJPG(urlString);*/
			String urlString=vv.getYimageurl();
			String facepath =urlString;
			String name = vv.getYname();
			String phone =  String.valueOf(vv.getYid());
			String sex = vv.getYsex();
			boolean msg =userService.addWhitePersion(facepath, name, phone, sex);
			if(msg){
				System.out.println("成导入00"+phone);
			}
		}
		return null;
	}
	
	
	/**
	 * 用户信息列表展示wubohui
	 */
	@RequestMapping(value="/Listwubohui",method=RequestMethod.GET)
	public String Listwubohui(String pageNow, Model model){	
			this.userService.showwubohui(pageNow,model);
			return "testshowindex";
		}
	
	/**
	 * 用户信息列表展示wubohui
	 */
	@RequestMapping(value="/Listwubohui2",method=RequestMethod.GET)
	@ResponseBody
	public test1 Listwubohui2(){
		test1 t = new test1();
		t=userService.showwubohui2();
	
			return t;
		}
	
	/**
	 * 彩之云授权人员允许
	 */
	@RequestMapping(value="/upUserczyuser",method=RequestMethod.POST)
	@ResponseBody
	public Returnxx upUserczyuser(String id,String auto,String detailed) throws Throwable{
		Returnxx rb = new Returnxx();
		rb= userService.upuserczy(id,auto,detailed);
		return rb;
	}
	
	/**
	 * 增量备份
	 */
	@RequestMapping(value="/Incrementalandbackup",method=RequestMethod.POST,produces={"text/html;charset=UTF-8"})
	@ResponseBody
	public String Incrementalandbackup(String starttime,String endtime){
		String msg = userService.Incrementalandbackupservice(starttime, endtime);
		return msg;
	}
	
	
	/**
	 * 测试
	 * @throws Exception 
	 */
	@RequestMapping(value="/Testtime",method=RequestMethod.GET,produces={"text/html;charset=UTF-8"})
	@ResponseBody
	public String  Testtime() throws Exception{
		userService.Testtime();
		String msg="成功";
		return msg;
	}
	
}
